import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import cargoApi from '@/api/cargo'
import inventoryApi from '@/api/inventory'

/**
 * 货物状态管理
 */
export const useCargoStore = defineStore('cargo', () => {
  // 状态定义
  const loading = ref(false)
  const cargoList = ref([])
  const cargoDetail = ref(null)
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })

  /**
   * 获取货物列表
   * @param {Object} params - 查询参数
   * @returns {Promise} 货物列表数据
   */
  async function getCargoList(params = {}) {
    loading.value = true;
    
    try {
      // 使用传入的参数，而不是从store中取值
      const queryParams = {
        page_num: params.page_num || pagination.value.current || 1,
        page_size: params.page_size || pagination.value.pageSize || 10
      };
      
      // 添加其他查询参数
      if (params.keyword) queryParams.keyword = params.keyword;
      if (params.category_id) queryParams.category_id = params.category_id;
      if (params.status !== undefined) queryParams.status = params.status;
      
      const response = await cargoApi.getCargoList(queryParams);
      console.log('后端返回的货物列表数据:', response);
      
      if (response.code === 0) {
        // 确保数据是数组格式
        if (response.data && Array.isArray(response.data)) {
          // 单纯的数组数据，没有分页信息
          cargoList.value = response.data;
          pagination.value.total = response.data.length;
        } else if (response.data && response.data.list) {
          // 带分页信息的数据结构
          cargoList.value = response.data.list || [];
          pagination.value.total = response.data.total || 0;
          
          // 如果当前页没有数据但total>0，可能是最后一页已经没有数据了
          if (cargoList.value.length === 0 && pagination.value.total > 0 && pagination.value.current > 1) {
            console.log('当前页没有数据，尝试切换到上一页');
            pagination.value.current -= 1;
            return getCargoList({ ...params, page_num: pagination.value.current });
          }
        } else {
          // 未知格式，使用空数组
          cargoList.value = [];
          pagination.value.total = 0;
        }
        
        // 更新分页信息
        pagination.value.current = parseInt(queryParams.page_num);
        pagination.value.pageSize = parseInt(queryParams.page_size);
        
        return {
          success: true,
          data: {
            list: cargoList.value,
            pagination: pagination.value
          }
        };
      } else {
        Message.error(response.message || '获取货物列表失败');
        return {
          success: false,
          message: response.message || '获取货物列表失败'
        };
      }
    } catch (error) {
      console.error('获取货物列表异常:', error);
      Message.error('获取货物列表失败: ' + (error.message || '未知错误'));
      return {
        success: false,
        message: error.message || '未知错误'
      };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 获取货物详情
   * @param {Number} id - 货物ID
   * @returns {Promise} 请求结果
   */
  async function getCargoDetail(id) {
    loading.value = true
    try {
      const response = await cargoApi.getCargoDetail(id)
      
      if (response.code === 0) {
        cargoDetail.value = response.data
        return { success: true, data: cargoDetail.value }
      }
      
      Message.error(response.message || '获取货物详情失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('获取货物详情失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建货物
   * @param {Object} data - 货物数据
   * @returns {Promise} 创建结果
   */
  async function createCargo(data) {
    loading.value = true;
    try {
      const response = await cargoApi.createCargo(data);
      
      if (response.code === 0) {
        Message.success('创建货物成功');
        return { success: true, data: response.data };
      }
      
      Message.error(response.message || '创建货物失败');
      return { success: false, message: response.message };
    } catch (error) {
      Message.error('创建货物失败: ' + (error.message || '未知错误'));
      return { success: false, message: error.message || '未知错误' };
    } finally {
      loading.value = false;
    }
  }

  /**
   * 更新货物
   * @param {Number} id - 货物ID
   * @param {Object} data - 货物数据
   * @returns {Promise} 请求结果
   */
  async function updateCargo(id, data) {
    loading.value = true
    try {
      const response = await cargoApi.updateCargo(id, data)
      
      if (response.code === 0) {
        Message.success('更新货物成功')
        return { success: true }
      }
      
      Message.error(response.message || '更新货物失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('更新货物失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除货物
   * @param {Number} id - 货物ID
   * @returns {Promise} 请求结果
   */
  async function deleteCargo(id) {
    loading.value = true
    try {
      const response = await cargoApi.deleteCargo(id)
      
      if (response.code === 0) {
        Message.success('删除货物成功')
        return { success: true }
      }
      
      Message.error(response.message || '删除货物失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('删除货物失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量删除货物
   * @param {Array} ids - 货物ID数组
   * @returns {Promise} 请求结果
   */
  async function batchDeleteCargos(ids) {
    loading.value = true
    try {
      const response = await cargoApi.batchDeleteCargos(ids)
      
      if (response.code === 0) {
        Message.success('批量删除货物成功')
        return { success: true }
      }
      
      Message.error(response.message || '批量删除货物失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('批量删除货物失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 导入货物数据
   * @param {FormData} formData - 包含货物数据的表单
   * @returns {Promise} 请求结果
   */
  async function importCargos(formData) {
    loading.value = true
    try {
      const response = await cargoApi.importCargos(formData)
      
      if (response.code === 0) {
        Message.success('导入货物数据成功')
        return { success: true, data: response.data }
      }
      
      Message.error(response.message || '导入货物数据失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('导入货物数据失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 导出货物数据
   * @param {Object} params - 导出参数
   * @returns {Promise} 请求结果
   */
  async function exportCargos(params = {}) {
    loading.value = true
    try {
      const response = await cargoApi.exportCargos(params)
      
      // 处理文件下载
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = '货物数据.xlsx'
      link.click()
      URL.revokeObjectURL(link.href)
      
      Message.success('导出货物数据成功')
      return { success: true }
    } catch (error) {
      Message.error('导出货物数据失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新货物状态
   * @param {Number} id - 货物ID
   * @param {String} status - 货物状态
   * @returns {Promise} 请求结果
   */
  async function updateCargoStatus(id, status) {
    loading.value = true
    try {
      const response = await cargoApi.updateCargoStatus(id, status)
      
      if (response.code === 0) {
        Message.success('更新货物状态成功')
        return { success: true }
      }
      
      Message.error(response.message || '更新货物状态失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('更新货物状态失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量更新货物状态
   * @param {Array} ids - 货物ID数组
   * @param {String} status - 货物状态
   * @returns {Promise} 请求结果
   */
  async function batchUpdateCargoStatus(ids, status) {
    loading.value = true
    try {
      const response = await cargoApi.batchUpdateCargoStatus(ids, status)
      
      if (response.code === 0) {
        Message.success('批量更新货物状态成功')
        return { success: true }
      }
      
      Message.error(response.message || '批量更新货物状态失败')
      return { success: false, message: response.message }
    } catch (error) {
      Message.error('批量更新货物状态失败: ' + (error.message || '未知错误'))
      return { success: false, message: error.message || '未知错误' }
    } finally {
      loading.value = false
    }
  }

  /**
   * 设置分页信息
   * @param {Number} current - 当前页码
   * @param {Number} pageSize - 每页条数
   */
  function setPagination(current, pageSize) {
    pagination.value.current = current
    pagination.value.pageSize = pageSize
  }

  /**
   * 获取指定仓库中有库存的商品列表
   * @param {Number} warehouseId - 仓库ID
   * @returns {Promise} 商品列表数据，包含库存信息
   */
  async function getInventoryProductList(warehouseId) {
    if (!warehouseId) {
      Message.warning('请先选择仓库');
      return [];
    }
    
    loading.value = true;
    try {
      // 调用获取仓库库存商品的API
      const response = await inventoryApi.getWarehouseProducts(warehouseId);
      
      if (response && response.code === 0) {
        // 将库存信息添加到商品列表中
        cargoList.value = response.data || [];
        return cargoList.value;
      } else {
        Message.error(response?.message || '获取库存商品失败');
        return [];
      }
    } catch (error) {
      console.error('获取库存商品失败:', error);
      Message.error('获取库存商品失败');
      return [];
    } finally {
      loading.value = false;
    }
  }

  return {
    loading,
    cargoList,
    cargoDetail,
    pagination,
    getCargoList,
    getCargoDetail,
    createCargo,
    updateCargo,
    deleteCargo,
    batchDeleteCargos,
    importCargos,
    exportCargos,
    updateCargoStatus,
    batchUpdateCargoStatus,
    setPagination,
    getInventoryProductList
  }
}) 